﻿using System;
using log4net;

namespace XieCan.AspMVC.Log4net
{
    /// <summary>
    /// log4net扩展类
    /// </summary>
    public static class Log4netEx
    {
        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <remarks>需提前配置log4net</remarks>
        /// <typeparam name="T">扩展类型</typeparam>
        /// <param name="t">扩展对象</param>
        /// <param name="message">日志内容</param>
        /// <param name="type">日志类型，默认INFO</param>
        /// <param name="exception">异常信息</param>
        public static void Log4<T>(this T t, string message, Log4Type type = Log4Type.Info, Exception exception = null)
        {
            var log = new Log4Model()
            {
                Exception = exception == null ? "" : exception.Message,
                Message = message,
                LogType = type
            };
            t.Log4(log, exception);
        }

        /// <summary>
        /// 记录操作日志
        /// </summary>
        /// <remarks>需提前配置log4net</remarks>
        /// <typeparam name="T">扩展类型</typeparam>
        /// <param name="t">扩展对象</param>
        /// <param name="message">日志内容</param>
        /// <param name="type">日志类型，默认INFO</param>
        /// <param name="exception">异常信息</param>
        private static void Log4<T>(this T t, Log4Model log4, Exception exception = null)
        {
            ILog log = null;
            var name = t.GetType().FullName;
            foreach (var logger in LogManager.GetCurrentLoggers())
            {
                if (logger.Logger.Name == name)
                {
                    log = logger;
                    break;
                }
            };
            if (log == null)
            {
                log = LogManager.GetLogger(name);
            }

            switch (log4.LogType)
            {
                case Log4Type.Debug:
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(log4, exception);
                    }
                    break;
                case Log4Type.Info:
                    if (log.IsInfoEnabled)
                    {
                        log.Info(log4, exception);
                    }
                    break;
                case Log4Type.Warn:
                    if (log.IsWarnEnabled)
                    {
                        log.Warn(log4, exception);
                    }
                    break;
                case Log4Type.Error:
                    if (log.IsErrorEnabled)
                    {
                        log.Error(log4, exception);
                    }
                    break;
                case Log4Type.Fatal:
                    if (log.IsFatalEnabled)
                    {
                        log.Fatal(log4, exception);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}

